# Maintainer: Felix Yan <felixonmars@archlinux.org>

# ALARM: Kevin Mihelich <kevin@archlinuxarm.org>
#  - disable lto via -DCMAKE_INTERPROCEDURAL_OPTIMIZATION=OFF

pkgbase=opencc
pkgname=(opencc opencc-doc)
pkgver=1.1.8
pkgrel=1
pkgdesc="Library for Open Chinese Convert"
url="https://github.com/BYVoid/OpenCC"
arch=('x86_64')
license=('Apache')
makedepends=('git' 'chrpath' 'cmake' 'darts' 'doxygen' 'marisa' 'pybind11' 'python-setuptools'
             'python-wheel' 'rapidjson' 'tclap' 'gtest')
source=("git+https://github.com/BYVoid/OpenCC.git#tag=ver.$pkgver"
        8f3a5b4b201f091713cb4e2b1b5883a4b12d10b2.patch)
sha512sums=('c5ffe2223e5cf3c2a3079128e6eefa74db083c32897f46ae58c981f3fe057cff045c4fed22266d4fe9170cf689169d4d8023b35da058c52d3a8f3034ca0ca8b2'
            'febade61cc1734db891234484893128519dffc198f80883fc4838534684f91db2a21641252615820ae9bedffce52451535ea2717a40958b80ea82590850b90ac')

prepare() {
  cd OpenCC
  rm -r deps

  # as of opencc 1.1.8 there is no clean way to disable duplicated building of the clib again. plus, the installation is broken as well.
  # let's revert the offending commit for now.
  patch -Rp1 -i ../8f3a5b4b201f091713cb4e2b1b5883a4b12d10b2.patch
}

build() {
  cd OpenCC
  cmake -DCMAKE_INSTALL_PREFIX=/usr -DBUILD_DOCUMENTATION:BOOL=ON -DBUILD_PYTHON:BOOL=ON \
        -DUSE_SYSTEM_MARISA:BOOL=ON -DUSE_SYSTEM_PYBIND11:BOOL=ON -DUSE_SYSTEM_RAPIDJSON:BOOL=ON \
        -DUSE_SYSTEM_TCLAP:BOOL=ON -DUSE_SYSTEM_DARTS:BOOL=ON -DENABLE_GTEST:BOOL=ON \
        -DUSE_SYSTEM_GTEST:BOOL=ON -DCMAKE_INTERPROCEDURAL_OPTIMIZATION=OFF
  make

  cp opencc_clib.*.so python/opencc/clib/
  python setup.py build
}

check() {
  cd OpenCC
  make test
}

package_opencc() {
  pkgdesc="Library for Open Chinese Convert"
  depends=('marisa')

  cd OpenCC
  make DESTDIR="$pkgdir" install
  python setup.py install --root="$pkgdir" --optimize=1

  # Hack to make opencc's python binding to use system opencc's configs
  local python_version=$(python -c 'import sys; print(".".join(map(str, sys.version_info[:2])))')
  mkdir "$pkgdir"/usr/lib/"python$python_version"/site-packages/opencc/clib/share
  ln -s ../../../../../../share/opencc "$pkgdir"/usr/lib/"python$python_version"/site-packages/opencc/clib/share/

  # Remove insecure RPath
  chrpath --delete "$pkgdir"/usr/lib/"python$python_version"/site-packages/opencc/clib/*.so

  # Remove docs - install in split package
  rm -r "$pkgdir/usr/share/opencc/doc"
}

package_opencc-doc() {
  pkgdesc="Documentation for Library for Open Chinese Convert"

  cd OpenCC/doc
  make DESTDIR="$pkgdir" install
}
